const BASE_URL = 'http://localhost:3000/api';

const request = (url, options = {}) => {
  return new Promise((resolve, reject) => {
    const token = wx.getStorageSync('token');
    
    wx.request({
      url: `${BASE_URL}${url}`,
      ...options,
      header: {
        'Content-Type': 'application/json',
        'Authorization': token ? `Bearer ${token}` : '',
        ...options.header
      },
      success: (res) => {
        if (res.statusCode >= 200 && res.statusCode < 300) {
          resolve(res.data);
        } else if (res.statusCode === 401) {
          // token过期或无效，清除本地存储并跳转到登录页
          wx.removeStorageSync('token');
          const app = getApp();
          app.globalData.hasLogin = false;
          app.globalData.userInfo = null;
          
          wx.showToast({
            title: '请重新登录',
            icon: 'none'
          });
          
          wx.navigateTo({
            url: '/pages/login/login'
          });
          
          reject(new Error('未授权'));
        } else {
          reject(new Error(res.data.error || '请求失败'));
        }
      },
      fail: (error) => {
        reject(new Error('网络错误'));
      }
    });
  });
};

// 文件上传方法
const upload = (url, filePath, formData = {}) => {
  const token = wx.getStorageSync('token')
  
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url: `${BASE_URL}${url}`,
      filePath: filePath,
      name: 'file',
      formData: formData,
      header: token ? {
        'Authorization': `Bearer ${token}`
      } : {},
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          resolve(data)
        } catch (error) {
          reject(new Error('解析响应数据失败'))
        }
      },
      fail: (error) => {
        reject(error)
      }
    })
  })
}

const get = (url, params = {}) => {
  return request(url, {
    method: 'GET',
    data: params
  });
};

const post = (url, data = {}) => {
  return request(url, {
    method: 'POST',
    data
  });
};

const put = (url, data = {}) => {
  return request(url, {
    method: 'PUT',
    data
  });
};

const del = (url) => {
  return request(url, {
    method: 'DELETE'
  });
};

module.exports = {
  get,
  post,
  put,
  del,
  upload
}; 